package thread;

import java.util.concurrent.*;

/**
 * @author: 成金乘
 * @date: 2023/1/9 14:52
 * @description:
 */
//编写代码, 实现线程池案例
class MyThreadPool{
    //创建一个阻塞队列
    private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
    //提供构造方法,接收线程数量
    public MyThreadPool(int n){
        for (int i = 0;i < n;i++){
            //创建出线程
            Thread t = new Thread(()->{
               while (true){
                   //队列不为空取出任务,为空阻塞
                   try {
                       Runnable runnable = queue.take();
                       runnable.run();
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
               }
            });
            t.start();
        }
    }
    //注册任务交给线程池
    public void submit(Runnable runnable) {
        try {
            queue.put(runnable);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

}

public class ThreadDemo12 {
    public static void main(String[] args) {
        MyThreadPool pool = new MyThreadPool(10);
        for (int i = 0;i < 100;i++){
            int n = i;
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello,ni,hao "+n);
                }
            });
        }
    }
}

//Java 标准库线程池的创建方式总共有几种？分别使用代码创建并演示一下
//有7种
class MyThread1{
    public static void main(String[] args) {
        //创建一个固定大小的线程池,可以控制并发的线程数
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);
        //创建一个可以缓存的线程池,若线程数超过任务所需,多余的线程会缓存一段时间后被回收,无可用线程则创建新的线程
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        //创建只有一个线程的线程池,可以保证先进先出的执行顺序
        ExecutorService sad = Executors.newSingleThreadExecutor();
        //创建一个可以指定线程大小,执行延时任务的线程池
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
        //创建一个单线程,可以执行延时任务的线程池
        ScheduledExecutorService s = Executors.newSingleThreadScheduledExecutor();
        //创建一个指定大小,抢占式执行的线程池,执行任务顺序不确定
        ExecutorService workStealingPool = Executors.newWorkStealingPool(10);
        //自定义线程池,创建时最多提供七个参数可供设置
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5,10,10,
                TimeUnit.SECONDS,new LinkedBlockingQueue<>(10));
    }
}
